// 清除对象空参数
export function deleteEmptyFields(object: Object) {
  for (let item in object) {
    if (object[item] === null || object[item] === undefined || object[item].toString().trim() === "") {
      delete object[item];
    }
  }
  return object;
}

/*时间格式化 YYYY-MM-DD
 flag: 时间拼接符
*/
export function birthdayFormat(data: any, flag: string) {
  if (data) {
    let time = new Date(data);
    let y = time.getFullYear();
    let m = time.getMonth() + 1 < 10 ? "0" + (time.getMonth() + 1) : time.getMonth() + 1;
    let d = time.getDate() < 10 ? "0" + time.getDate() : time.getDate();
    return y + flag + m + flag + d;
  }
}

// 深拷贝
export function deepClone(target) {
  const map = new WeakMap();

  function isObject(target) {
    return (typeof target === "object" && target) || typeof target === "function";
  }

  function clone(data) {
    if (!isObject(data)) {
      return data;
    }
    if ([Date, RegExp].includes(data.constructor)) {
      return new data.constructor(data);
    }
    if (typeof data === "function") {
      return new Function("return " + data.toString())();
    }
    const exist = map.get(data);
    if (exist) {
      return exist;
    }
    if (data instanceof Map) {
      const result = new Map();
      map.set(data, result);
      data.forEach((val, key) => {
        if (isObject(val)) {
          result.set(key, clone(val));
        } else {
          result.set(key, val);
        }
      });
      return result;
    }
    if (data instanceof Set) {
      const result = new Set();
      map.set(data, result);
      data.forEach(val => {
        if (isObject(val)) {
          result.add(clone(val));
        } else {
          result.add(val);
        }
      });
      return result;
    }
    const keys = Reflect.ownKeys(data);
    const allDesc = Object.getOwnPropertyDescriptors(data);
    const result = Object.create(Object.getPrototypeOf(data), allDesc);
    map.set(data, result);
    keys.forEach(key => {
      const val = data[key];
      if (isObject(val)) {
        result[key] = clone(val);
      } else {
        result[key] = val;
      }
    });
    return result;
  }

  return clone(target);
}
